import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  Spin, 
  Alert, 
  Button, 
  Row, 
  Col, 
  Progress,
  Timeline,
  Tag,
  Statistic
} from 'antd';
import { 
  FaChartBar, 
  FaSync,
  FaExclamationTriangle,
  FaCheckCircle,
  FaRunning,
  FaPauseCircle
} from 'react-icons/fa';
import { useAuthStore } from '../../../stores/authStore';
import { useThemeStore } from '../../../stores/themeStore';
import { getTheme } from '../../../theme/config';
import CustomTable from '../../../components/custom/CustomTable';
import type { ColumnsType } from 'antd/es/table';

interface JobStatus {
  id: string;
  name: string;
  status: 'running' | 'completed' | 'failed' | 'pending' | 'paused';
  progress: number;
  startTime: string;
  duration: string;
  itemsScraped: number;
  errors: number;
  spider: string;
  project: string;
}

interface SystemStatus {
  cpu: number;
  memory: number;
  disk: number;
  network: number;
}

const CrawlerMonitorPage: React.FC = () => {
  const navigate = useNavigate();
  const { isAuthenticated } = useAuthStore();
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [jobStatus, setJobStatus] = useState<JobStatus[]>([]);
  const [systemStatus, setSystemStatus] = useState<SystemStatus>({
    cpu: 45,
    memory: 68,
    disk: 32,
    network: 75
  });

  // 检查认证状态
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
    }
  }, [isAuthenticated, navigate]);

  // 模拟获取任务状态
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // 模拟数据
        const mockJobStatus: JobStatus[] = [
          {
            id: '1',
            name: '电商商品爬虫',
            status: 'running',
            progress: 75,
            startTime: '2023-12-01 14:30:22',
            duration: '2小时35分钟',
            itemsScraped: 12543,
            errors: 2,
            spider: 'product_spider',
            project: 'ecommerce_scraper'
          },
          {
            id: '2',
            name: '新闻文章爬虫',
            status: 'completed',
            progress: 100,
            startTime: '2023-12-01 12:15:45',
            duration: '1小时45分钟',
            itemsScraped: 8765,
            errors: 0,
            spider: 'article_spider',
            project: 'news_scraper'
          },
          {
            id: '3',
            name: '社交媒体爬虫',
            status: 'failed',
            progress: 30,
            startTime: '2023-12-01 10:22:18',
            duration: '0小时45分钟',
            itemsScraped: 2345,
            errors: 15,
            spider: 'post_spider',
            project: 'social_scraper'
          }
        ];
        
        setJobStatus(mockJobStatus);
      } catch (err) {
        console.error('获取监控数据失败:', err);
        setError('获取监控数据失败: ' + (err instanceof Error ? err.message : '未知错误'));
      } finally {
        setLoading(false);
      }
    };

    if (isAuthenticated) {
      fetchData();
      
      // 模拟实时更新
      const interval = setInterval(() => {
        setSystemStatus({
          cpu: Math.floor(Math.random() * 30) + 30,
          memory: Math.floor(Math.random() * 40) + 50,
          disk: Math.floor(Math.random() * 20) + 20,
          network: Math.floor(Math.random() * 50) + 50
        });
      }, 5000);
      
      return () => clearInterval(interval);
    }
  }, []); // 空依赖数组确保只在组件挂载时执行一次

  // 刷新数据
  const refreshData = async () => {
    try {
      setLoading(true);
      // 模拟刷新
      await new Promise(resolve => setTimeout(resolve, 1000));
    } catch (err) {
      setError('刷新失败: ' + (err instanceof Error ? err.message : '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取状态图标
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'running':
        return <FaRunning style={{ color: '#52c41a' }} />;
      case 'completed':
        return <FaCheckCircle style={{ color: '#52c41a' }} />;
      case 'failed':
        return <FaExclamationTriangle style={{ color: '#ff4d4f' }} />;
      case 'pending':
        return <FaPauseCircle style={{ color: '#faad14' }} />;
      case 'paused':
        return <FaPauseCircle style={{ color: '#faad14' }} />;
      default:
        return <FaPauseCircle style={{ color: '#faad14' }} />;
    }
  };

  // 获取状态标签颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'running':
        return 'success';
      case 'completed':
        return 'success';
      case 'failed':
        return 'error';
      case 'pending':
        return 'warning';
      case 'paused':
        return 'warning';
      default:
        return 'default';
    }
  };

  // 任务状态表格列定义
  const columns: ColumnsType<JobStatus> = [
    {
      title: '任务名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <span style={{ color: theme.textPrimary, fontWeight: 'bold' }}>{text}</span>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag icon={getStatusIcon(status)} color={getStatusColor(status)}>
          {status === 'running' && '运行中'}
          {status === 'completed' && '已完成'}
          {status === 'failed' && '失败'}
          {status === 'pending' && '待处理'}
          {status === 'paused' && '已暂停'}
        </Tag>
      )
    },
    {
      title: '进度',
      dataIndex: 'progress',
      key: 'progress',
      render: (progress: number) => (
        <Progress percent={progress} size="small" />
      )
    },
    {
      title: '数据量',
      dataIndex: 'itemsScraped',
      key: 'itemsScraped',
      render: (items: number) => (
        <span style={{ color: theme.textPrimary }}>{items.toLocaleString()}</span>
      )
    },
    {
      title: '错误数',
      dataIndex: 'errors',
      key: 'errors',
      render: (errors: number) => (
        <span style={{ color: errors > 0 ? '#ff4d4f' : theme.textPrimary }}>
          {errors}
        </span>
      )
    },
    {
      title: '运行时间',
      dataIndex: 'duration',
      key: 'duration',
      render: (duration: string) => (
        <span style={{ color: theme.textPrimary }}>{duration}</span>
      )
    }
  ];

  // 获取卡片样式
  const getCardStyle = () => ({
    background: theme.cardBackground,
    border: `1px solid ${theme.cardBorder}`,
    borderRadius: '12px',
    boxShadow: mode === 'light' ? theme.cardShadow : 'none'
  });

  if (!isAuthenticated) {
    return null;
  }

  return (
    <div style={{ padding: '24px', color: theme.textPrimary }}>
      <div style={{ marginBottom: '24px' }}>
        <h1 style={{ 
          color: theme.glowColor, 
          fontSize: '28px',
          fontWeight: 'bold',
          marginBottom: '8px'
        }}>
          <FaChartBar style={{ marginRight: '12px' }} />
          爬虫监控面板
        </h1>
        <p style={{ 
          fontSize: '16px',
          opacity: 0.8,
          marginBottom: '24px',
          color: theme.textSecondary
        }}>
          实时监控爬虫任务状态和系统资源使用情况
        </p>
      </div>

      {/* 操作栏 */}
      <div style={{ marginBottom: '24px', textAlign: 'right' }}>
        <Button 
          icon={<FaSync />}
          onClick={refreshData}
          style={{ 
            background: theme.cardBackground,
            border: `1px solid ${theme.cardBorder}`,
            color: theme.textPrimary
          }}
        >
          刷新
        </Button>
      </div>

      {/* 系统状态卡片 */}
      <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} md={6}>
          <Card 
            style={getCardStyle()}
            bodyStyle={{ padding: '16px' }}
          >
            <Statistic
              title="CPU使用率"
              value={systemStatus.cpu}
              suffix="%"
              valueStyle={{ color: systemStatus.cpu > 80 ? '#ff4d4f' : theme.glowColor }}
            />
            <Progress percent={systemStatus.cpu} showInfo={false} status={systemStatus.cpu > 80 ? 'exception' : 'normal'} />
          </Card>
        </Col>

        <Col xs={24} sm={12} md={6}>
          <Card 
            style={getCardStyle()}
            bodyStyle={{ padding: '16px' }}
          >
            <Statistic
              title="内存使用率"
              value={systemStatus.memory}
              suffix="%"
              valueStyle={{ color: systemStatus.memory > 80 ? '#ff4d4f' : theme.glowColor }}
            />
            <Progress percent={systemStatus.memory} showInfo={false} status={systemStatus.memory > 80 ? 'exception' : 'normal'} />
          </Card>
        </Col>

        <Col xs={24} sm={12} md={6}>
          <Card 
            style={getCardStyle()}
            bodyStyle={{ padding: '16px' }}
          >
            <Statistic
              title="磁盘使用率"
              value={systemStatus.disk}
              suffix="%"
              valueStyle={{ color: systemStatus.disk > 80 ? '#ff4d4f' : theme.glowColor }}
            />
            <Progress percent={systemStatus.disk} showInfo={false} status={systemStatus.disk > 80 ? 'exception' : 'normal'} />
          </Card>
        </Col>

        <Col xs={24} sm={12} md={6}>
          <Card 
            style={getCardStyle()}
            bodyStyle={{ padding: '16px' }}
          >
            <Statistic
              title="网络使用率"
              value={systemStatus.network}
              suffix="%"
              valueStyle={{ color: systemStatus.network > 80 ? '#ff4d4f' : theme.glowColor }}
            />
            <Progress percent={systemStatus.network} showInfo={false} status={systemStatus.network > 80 ? 'exception' : 'normal'} />
          </Card>
        </Col>
      </Row>

      {/* 任务状态 */}
      <Row gutter={[24, 24]}>
        <Col xs={24} lg={16}>
          <Card 
            style={getCardStyle()}
          >
            <h2 style={{ 
              color: theme.textPrimary, 
              fontSize: '20px',
              fontWeight: 'bold',
              marginBottom: '16px'
            }}>
              任务状态
            </h2>
            
            {error ? (
              <Alert
                message="错误"
                description={error}
                type="error"
                showIcon
                style={{ marginBottom: '16px' }}
              />
            ) : null}
            
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin size="large" tip="加载中..." />
              </div>
            ) : (
              <CustomTable 
                dataSource={jobStatus}
                columns={columns}
                rowKey="id"
                pagination={false}
                locale={{
                  emptyText: (
                    <div style={{ padding: '40px', textAlign: 'center', color: theme.textSecondary }}>
                      <FaChartBar style={{ fontSize: '48px', marginBottom: '16px', opacity: 0.5, color: theme.glowColor }} />
                      <p>暂无任务状态数据</p>
                    </div>
                  )
                }}
              />
            )}
          </Card>
        </Col>
        
        <Col xs={24} lg={8}>
          <Card 
            style={getCardStyle()}
          >
            <h2 style={{ 
              color: theme.textPrimary, 
              fontSize: '20px',
              fontWeight: 'bold',
              marginBottom: '16px'
            }}>
              最近活动
            </h2>
            
            <Timeline 
              pending="等待更多活动..." 
              style={{ color: theme.textPrimary }}
            >
              <Timeline.Item color="green">
                <p style={{ color: theme.textPrimary }}>电商商品爬虫任务开始运行</p>
                <p style={{ fontSize: '12px', opacity: 0.8, color: theme.textSecondary }}>2023-12-01 14:30:22</p>
              </Timeline.Item>
              <Timeline.Item color="blue">
                <p style={{ color: theme.textPrimary }}>新闻文章爬虫任务完成</p>
                <p style={{ fontSize: '12px', opacity: 0.8, color: theme.textSecondary }}>2023-12-01 14:00:45</p>
              </Timeline.Item>
              <Timeline.Item color="red">
                <p style={{ color: theme.textPrimary }}>社交媒体爬虫任务失败</p>
                <p style={{ fontSize: '12px', opacity: 0.8, color: theme.textSecondary }}>2023-12-01 11:07:18</p>
              </Timeline.Item>
              <Timeline.Item color="blue">
                <p style={{ color: theme.textPrimary }}>新闻文章爬虫任务开始运行</p>
                <p style={{ fontSize: '12px', opacity: 0.8, color: theme.textSecondary }}>2023-12-01 12:15:45</p>
              </Timeline.Item>
            </Timeline>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default CrawlerMonitorPage;